package com.sunkyc.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sunkyc.commons.annotation.ReqLog;
import com.sunkyc.commons.entity.R;
import com.sunkyc.commons.exception.CustomerException;
import com.sunkyc.framework.system.entity.SysMenu;
import com.sunkyc.framework.system.entity.SysRoleMenu;
import com.sunkyc.framework.system.service.SysMenuService;
import com.sunkyc.framework.system.service.SysRoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author sunkyc
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/sysMenu")
@RequiredArgsConstructor
@Api(value = "系统菜单前端控制器", tags = {"系统菜单管理"})
public class SysMenuController {
    private final SysMenuService baseService;
    private final SysRoleMenuService sysRoleMenuService;


    @GetMapping("/treeForManage")
    @ApiOperation("菜单列表")
    @SaCheckPermission("system-menu-list")
    public R<List<Tree<String>>>  treeForManage(){
        return R.ok(baseService.treeList());
    }


    @PostMapping
    @ApiOperation("菜单添加")
    @SaCheckPermission("system-menu-add")
    @ReqLog
    public R<Void> addMenu(@RequestBody @Validated SysMenu sysMenu){
        return R.result(baseService.addMenu(sysMenu));
    }


    @PutMapping
    @ApiOperation("菜单修改")
    @SaCheckPermission("system-menu-update")
    @ReqLog
    public R<Void> editMenu(@RequestBody @Validated SysMenu sysMenu){
        return R.result(baseService.editMenu(sysMenu));
    }


    @DeleteMapping("/{menuId}")
    @ApiOperation("菜单删除")
    @SaCheckPermission("system-menu-delete")
    @ReqLog
    public R<Void> delMenuById(@PathVariable Long menuId){
        // 查询当前是否分配
        if(sysRoleMenuService.count(Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getMenuId,menuId)) > 0){
            throw new CustomerException("菜单已经分配,请检查角色权限");
        }
        // 查询是否有子菜单
        if(baseService.count(Wrappers.lambdaQuery(SysMenu.class).eq(SysMenu::getParentId,menuId))>0){
            throw new CustomerException("当前菜单存在子菜单,请检查");
        }
        return R.result(baseService.delMenuById(menuId));
    }





}
